package com.twoscreen;

import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class ResponseServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger("com.twoscreen.ResponseServlet.java");
	private static final long serialVersionUID = 1L;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) {
		log.info("Request received");
		//Get the params passed
		String reply = null;
		long questionId = -1;
		String viewerId = null;
		
		if (request.getParameter("reply") != null) {
			reply = request.getParameter("reply");
			log.info("reply received: " + reply);
		}
		if (request.getParameter("qId") != null) {
			questionId = Long.parseLong(request.getParameter("qId"));
			log.info("questionId received: " + questionId);
		}
		if (request.getParameter("viewer") != null) {
			viewerId = request.getParameter("viewer");
			log.info("viewer received: " + viewerId);
		}
		
		log.info("Info received: reply: " + reply +
				" questionId: " + questionId +
				" viewerID: " + viewerId);
		
		//Get the user for validation
		UserService userService = UserServiceFactory.getUserService();
		User user = null;
		Boolean validUser = false;
		try {
			user = userService.getCurrentUser();
			validUser = Validator.checkGoogleUserViewerID(user, viewerId);
		} catch (Exception e) {
			log.warning("Error getting the user: " + e);
		}
		
		//Test if a reply is being submitted
		if (reply != null && questionId != -1 && viewerId != null && validUser == true) {
			log.info("Adding new response");
			//Add a new object
			new Response(reply, questionId, viewerId);
		}
		//No response as the user is in app and would cause a poor user experience
	}

}
